package com.bcfn.bshop.common.intercepter;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import com.bcfn.bshop.common.dto.DataGridDto;
import com.bcfn.bshop.common.dto.PageDto;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

/**
 * 分页处理拦截器。
 * @author LiangGuoNing
 * @create 2019年2月9日 下午9:26:18
 * @copyright
 * @modify
 */
@Component
@Aspect
public class PageIntercepter {

	public PageIntercepter() {
		System.out.println("PageIntercepter init");
	}
	
	@Pointcut("execution(* com.bcfn.bshop.*.service.*.search*(..))")
	public void pointcut() {}
	
	@Around("pointcut()")
	public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
		System.out.println("pointcut around");
		Object[] args = joinPoint.getArgs();
		if(args == null || args.length <= 0) {
			System.out.println("方法:" + joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + " 无参数或参数为null.");
			return null;
		}
		Object arg = args[0];
		if(arg == null) {
			System.out.println("方法:" + joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + " 参数为null.");
			return null;
		}
		if(!(arg instanceof PageDto)) {
			System.out.println(joinPoint.getTarget().getClass().getName() + " 没有继承：" + PageDto.class.getName());
			return null;
		}
		PageDto pageDto = (PageDto) arg;
		Page<?> page = PageHelper.startPage(pageDto.getPageNo(), pageDto.getPageSize());
		Object object = joinPoint.proceed();
		if(object instanceof DataGridDto) {
			DataGridDto<?> dataGridDto = (DataGridDto<?>) object;
			dataGridDto.setTotal(page.getTotal());
		}
		
		return object;
	}
}
